package me.shibor.study.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取cookies，设置cookies
 * @author shibor
 *
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		getCookies(request);
		
		addCookies(response);
		
	}
	
	private void getCookies(HttpServletRequest request) {
		
		System.out.println("getCookies:");
		Cookie[] cookies = request.getCookies();
		if(cookies != null)
		for(Cookie ck : cookies){
			System.out.println(ck.getName() + ":" + ck.getValue());
		}
	}
	
	private void addCookies(HttpServletResponse response) {
		
		
		Cookie ck1 = new Cookie("baidu", "www.baidu.com");
		Cookie ck2 = new Cookie("shibor", "localhost");
		//设置时效
		ck1.setMaxAge(60*60*24*7);
		ck2.setMaxAge(10);
		response.addCookie(ck1);
		response.addCookie(ck2);
	}

}
